const express = require("express");
const bodyParser = require("body-parser");
const uuid = require("uuid");
const cookieParser = require("cookie-parser") //页面间的传值
const expressSession = require("express-session"); //服务器端的传值
const cors = require("cors");

let app = express();

app.use(cors());

//配置静态资源
app.use(express.static("./../src/"));

//配置中间件
app.use(expressSession({
    genid: function() {
        return uuid.v1()
    },
    maxAge: 1000 * 60 * 20,
    secret: "itZhi",
    resave: true,
    saveUninitialized: true
}))

app.use(cookieParser("itZhi"));

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

let whiteList = ["/api/login", "/api/reg", "/api/list", "/api/ById"]; //白名单

app.use("*", (request, response, next) => {
    if (response.originalUrl == "/favicon.ico") {
        return;
    }

    //请求的路径带api的字眼
    if (request.originalUrl.indexOf("/api") != -1) {
        response.setHeader("Content-type", "application/json;charset=utf-8");
    }

    //如果session里没有数据说明没有登录,没有登录的话就只能访问白名单的接口
    if (request.session["userInfo"] == undefined || request.session["userInfo"] == null) {
        let isPass = whiteList.some(el => {
            return request.originalUrl.toLowerCase().indexOf(el.toLowerCase()) != -1
        })
        if (isPass) {
            next();
        } else {
            response.json({
                msg: "数据过期,请重新登录",
                status: -1
            })
        }
    } else {
        next();
    }
})


//路由
app.use("/api", require("./routes/apiRoute"));

app.listen(8080, () => {
    console.log("服务器启动完毕");
})